using Microsoft.AspNetCore.Http;
using Vin.Extension.Framework.Dto;
using Vin.Extension.Framework.Models;
using Vin.Extension.JwtBearer.Extension;
using Vin.Extension.JwtBearer.Tool;
using Vin.Extension.Redis.Cache;
using Vin.Tool.AspNetCore.Service;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.ConvertCategory;
using Vin.Tool.Domain.ExceptionModel;

namespace Vin.Extension.Framework.Base;

public class VinFrameworkBaseService : VinBaseService
{
    #region 授权用户

    public long? AccountId => string.IsNullOrEmpty(HttpContext.GetRealAccountId())
        ? null
        : HttpContext.GetRealAccountId().ToLong(); //GetVinTokenModel().RealAccountId;

    public string? Account => HttpContext.GetAccountName(); //GetVinTokenModel().AccountName;

    public long? UserId => string.IsNullOrEmpty(HttpContext.GetRealUserId())
        ? null
        : HttpContext.GetRealUserId().ToLong(); //GetVinTokenModel().RealUserId;

    public string? UserName => HttpContext.GetUserName(); //GetVinTokenModel().UserName;

    public VinTokenModel GetVinTokenModel()
    {
        // return VinSecurityTool.GetTokenModelByToken<VinTokenModel>() ?? throw new UnauthorizedException();
        return GetTokenModel<VinTokenModel>();
    }

    public VinTokenModel? GetVinTokenModelOrNull()
    {
        // return VinSecurityTool.GetTokenModelByToken<VinTokenModel>();
        return GetTokenModelOrNull<VinTokenModel>();
    }

    public T GetTokenModel<T>() where T : VinTokenModel
    {
        return GetTokenModelOrNull<T>() ?? throw new UnauthorizedException();
    }

    public T? GetTokenModelOrNull<T>() where T : VinTokenModel
    {
        return VinSecurityTool.GetTokenModelByToken<T>();
    }

    #endregion

    #region Redis

    public RedisCache RedisCache => GetRedisCache();

    public RedisCache GetRedisCache(int db = 0)
    {
        return RedisCacheManager.GetRedisCache(db);
    }

    #endregion
}